package com.cskaoyan.service;

import com.cskaoyan.bean.HandleOption;
import com.cskaoyan.bean.bo.OrderCommentBO;
import com.cskaoyan.bean.bo.OrderListWxBO;
import com.cskaoyan.bean.bo.OrderSubmitWxBO;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.OrderDetailWxVO;
import com.cskaoyan.bean.vo.OrderListWxVO;
import com.cskaoyan.bean.vo.OrderSubmitWxVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.Constant;
import com.cskaoyan.util.OrderHandleOption;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 订单的实现类
 *
 * @author chenxu
 * @since 2022/04/08 22:05
 */
@Service
public class OrderWxServiceImpl implements OrderWxService{

    @Autowired
    MarketOrderMapper orderMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MarketAddressMapper addressMapper;

    @Autowired
    MarketCartMapper cartMapper;

    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Autowired
    MarketCouponMapper couponMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;

    @Autowired
    MarketSystemMapper systemMapper;

    @Autowired
    MarketAftersaleMapper aftersaleMapper;

    @Transactional
    @Override
    public OrderSubmitWxVO submit(Integer userId, OrderSubmitWxBO orderSubmitBO) {
        //1.先通过adressId获取需要的值封进对象(user_id)
        MarketAddress address = addressMapper.selectByPrimaryKey(orderSubmitBO.getAddressId());

        //3.grouponRulesId获取团购规则信息
        MarketGrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(orderSubmitBO.getGrouponRulesId());

        //4.通过userCouponId获取用户用户使用信息
        MarketCouponUser couponUser = couponUserMapper.selectByPrimaryKey(orderSubmitBO.getUserCouponId());
        if (couponUser != null ){
            //修改优惠券使用状态
            couponUser.setStatus((short)1);
            couponUser.setUsedTime(new Date());
            couponUser.setUpdateTime(new Date());
            couponUserMapper.updateByPrimaryKey(couponUser);
        }
        //5.获取优惠券的信息
        MarketCoupon coupon = couponMapper.selectByPrimaryKey(orderSubmitBO.getCouponId());

        // 6.order_sn 订单编号;先获取当前时间的年月日，在随机生成一个6位数，进行拼接
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMdd");
        String format = dateFormat.format(date);

        //7.随机生成一个六位数
        Random random = new Random();
        String result = "";
        int length = 6;
        for (int i = 0; i < length; i++) {
            result += random.nextInt(10);
        }
        //获得订单编号：拼接时间和随机生成的六位数
        String ordersn = format + result;

        // 8.order_status 订单状态，订单状态101未付款
        Short orderStatus = 101;

        //售后状态
        Short afterSaleStatus = 0;


        //2.修改库存信息：通过caetId查找获取购物车信息 :先判断cartId的值：0 表示购物车下单   不为0，说明是立即购买下单的
        if (orderSubmitBO.getCartId() == 0) {
            MarketCartExample example = new MarketCartExample();
            //通过userId和checked状态查找cart
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
            List<MarketCart> marketCarts = cartMapper.selectByExample(example);
            //订单商品总费用
            double cartPrice = 0;
            //运费
            double freightPrice = 0;
            //订单待评价数量
            int comments = 0 ;

            //遍历marketCarts
            for (MarketCart marketCart : marketCarts) {
                Short cartGoodsNumber = marketCart.getNumber();
                //获得商品库存表
                MarketGoodsProduct marketGoodsProduct1 = goodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
                //减少商品库存
                Integer number = marketGoodsProduct1.getNumber() - cartGoodsNumber;
                marketGoodsProduct1.setNumber(number);
                marketGoodsProduct1.setUpdateTime(new Date());
                goodsProductMapper.updateByPrimaryKey(marketGoodsProduct1);

                //下单后购物车deletid要修改为true
                marketCart.setDeleted(true);
                cartMapper.updateByPrimaryKeySelective(marketCart);

                //订单费=为选中的商品价格相加
                BigDecimal price = marketCart.getPrice();
                double goodPrice = price.doubleValue();
                cartPrice += goodPrice;

                comments += cartGoodsNumber;

            }

            //运费：满一定价格就免邮
            MarketSystem marketSystem = systemMapper.selectByPrimaryKey(6);
            String freightMin = marketSystem.getKeyValue();
            //String类型转成bigdecimal类型
            //BigDecimal freightPriceMin = new BigDecimal(freightMin);
            //f (a.compareTo(b) == 1)
            //     System.out.println("a > b");


            //运费
            if ((new BigDecimal(cartPrice).compareTo(new BigDecimal(freightMin)) == -1)) {
                MarketSystem system = systemMapper.selectByPrimaryKey(8);
                BigDecimal freight = new BigDecimal(system.getKeyValue());
                double doubleValue = freight.doubleValue();
                freightPrice = doubleValue;
            }
            //订单关闭时间
            long currentTimeMillis = System.currentTimeMillis();
            currentTimeMillis += 30 * 60 * 1000;
            Date endTime = new Date(currentTimeMillis);


            //todo 用户积分
            //BigDecimal intergral = new BigDecimal("0.0");

            //订单费用 = goods_price + freight_price - coupon_price

            BigDecimal orderPrice = (new BigDecimal(cartPrice).add(new BigDecimal(freightPrice)));

            if (coupon != null){
                orderPrice.subtract(coupon.getDiscount());
            }

            //封装进order

            MarketOrder order = new MarketOrder();
            //用户id
            order.setUserId(userId);
            //订单编号
            order.setOrderSn(ordersn);
            //订单状态
            order.setOrderStatus(orderStatus);
            //售后状态
            order.setAftersaleStatus(afterSaleStatus);
            //收货人
            order.setConsignee(address.getName());
            //电话号码
            order.setMobile(address.getTel());
            //订单地址
            order.setAddress(address.getProvince() + address.getCity() + address.getCounty() + address.getAddressDetail());
            //订单说明信息
            order.setMessage(orderSubmitBO.getMessage());

            order.setGoodsPrice(new BigDecimal(cartPrice));

            //待评价订单数量
            order.setComments((short)comments);

            //订单运费
            order.setFreightPrice(new BigDecimal(freightPrice));
            //优惠券价格
            if (coupon != null) {
                order.setCouponPrice(coupon.getDiscount());
            }else order.setCouponPrice(new BigDecimal(0));


            order.setIntegralPrice(new BigDecimal(0));

            //订单的团购价格
            if (grouponRules != null) {
                order.setGrouponPrice(grouponRules.getDiscount());
            }else order.setGrouponPrice(new BigDecimal(0));
            //订单价格
            order.setOrderPrice(orderPrice);

            order.setActualPrice(orderPrice.subtract(new BigDecimal(0)));

            order.setAddTime(new Date());

            order.setEndTime(endTime);

            order.setUpdateTime(new Date());

            order.setDeleted(false);
            //todo
            order.setShipChannel(null);
            //创建订单
            orderMapper.insert(order);

            //todo 遍历cart创建一个订单商品表
            for (MarketCart cart : marketCarts) {
                MarketOrderGoods OrderGoods = new MarketOrderGoods();
                OrderGoods.setOrderId(order.getId());
                OrderGoods.setGoodsId(cart.getGoodsId());
                OrderGoods.setGoodsName(cart.getGoodsName());
                OrderGoods.setGoodsSn(cart.getGoodsSn());
                OrderGoods.setProductId(cart.getProductId());
                OrderGoods.setNumber(cart.getNumber());
                OrderGoods.setPrice(cart.getPrice());
                //todo
                OrderGoods.setSpecifications(cart.getSpecifications());
                OrderGoods.setPicUrl(cart.getPicUrl());
                OrderGoods.setComment(0);//0:可以评价
                OrderGoods.setAddTime(new Date());
                OrderGoods.setUpdateTime(new Date());
                OrderGoods.setDeleted(false);
                //添加到数据库
                orderGoodsMapper.insertSelective(OrderGoods);
            }

            //创建返回的Vo
            OrderSubmitWxVO orderSubmitWxVO = new OrderSubmitWxVO();
            orderSubmitWxVO.setGrouponLinkId(orderSubmitBO.getGrouponLinkId());
            orderSubmitWxVO.setOrderId(order.getId());

            return orderSubmitWxVO;

        }

        //立即购买的情况
        if (orderSubmitBO.getCartId() != 0) {
            MarketCart cart = cartMapper.selectByPrimaryKey(orderSubmitBO.getCartId());
            MarketGoodsProduct marketGoodsProduct = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
            marketGoodsProduct.setNumber(marketGoodsProduct.getNumber() - cart.getNumber());
            goodsProductMapper.updateByPrimaryKey(marketGoodsProduct);
            //修改购物车deleteId为true
            cart.setDeleted(true);
            cartMapper.updateByPrimaryKey(cart);

            //运费：满一定价格就免邮
            MarketSystem marketSystem = systemMapper.selectByPrimaryKey(6);
            String freightMin = marketSystem.getKeyValue();
            //String类型转成bigdecimal类型

            BigDecimal freightPrice = new BigDecimal(0);
            //f (a.compareTo(b) == 1)
            //     System.out.println("a > b");
            if ((cart.getPrice().compareTo(new BigDecimal(freightMin)) == 1)) {
                BigDecimal freightPrice2 = new BigDecimal(0);
                freightPrice = freightPrice2;
            }
            //运费
            if ((cart.getPrice().compareTo(new BigDecimal(freightMin)) == -1)) {

                MarketSystem freightPrice2 = systemMapper.selectByPrimaryKey(8);

                BigDecimal freightPrice3 = new BigDecimal(freightPrice2.getKeyValue());

                freightPrice = freightPrice3;
            }

            //订单关闭时间
            long currentTimeMillis = System.currentTimeMillis();
            currentTimeMillis += 30 * 60 * 1000;
            Date endTime = new Date(currentTimeMillis);
            //todo 用户积分
            BigDecimal intergral = new BigDecimal("0.0");

            //订单费用 = goods_price + freight_price - coupon_price
            BigDecimal orderPrice = cart.getPrice().add(freightPrice);
            if (orderSubmitBO.getCouponId() != 0){
                orderPrice.subtract(coupon.getDiscount());
            }

            //封装进order
            MarketOrder order = new MarketOrder();
            //用户id
            order.setUserId(userId);
            //订单编号
            order.setOrderSn(ordersn);
            //订单状态
            order.setOrderStatus(orderStatus);
            //售后状态
            order.setAftersaleStatus(afterSaleStatus);
            //收货人
            order.setConsignee(address.getName());
            //电话号码
            order.setMobile(address.getTel());
            //订单地址
            order.setAddress(address.getProvince() + address.getCity() + address.getCounty() + address.getAddressDetail());
            //订单说明信息
            order.setMessage(orderSubmitBO.getMessage());

            order.setComments((short)cart.getNumber());

            order.setGoodsPrice(cart.getPrice());

            //订单运费
            order.setFreightPrice(freightPrice);
            //优惠券价格
            if (coupon != null) {
                order.setCouponPrice(coupon.getDiscount());
            }

            order.setIntegralPrice(intergral);

            //订单的团购价格
            if (grouponRules != null) {
                order.setGrouponPrice(grouponRules.getDiscount());
            }else  order.setGrouponPrice(new BigDecimal(0));
            //订单价格
            order.setOrderPrice(orderPrice);

            order.setActualPrice(orderPrice.subtract(intergral));

            order.setAddTime(new Date());

            order.setEndTime(endTime);

            order.setUpdateTime(new Date());

            order.setDeleted(false);
            //todo
            order.setShipChannel(null);


            //创建订单
            orderMapper.insert(order);

            //创建一个订单商品表
            MarketOrderGoods OrderGoods = new MarketOrderGoods();
            OrderGoods.setOrderId(order.getId());
            OrderGoods.setGoodsId(cart.getGoodsId());
            OrderGoods.setGoodsName(cart.getGoodsName());
            OrderGoods.setGoodsSn(cart.getGoodsSn());
            OrderGoods.setProductId(cart.getProductId());
            OrderGoods.setNumber(cart.getNumber());
            OrderGoods.setPrice(cart.getPrice());
            //todo
            OrderGoods.setSpecifications(cart.getSpecifications());
            OrderGoods.setPicUrl(cart.getPicUrl());
            OrderGoods.setComment(0);//0:可以评价
            OrderGoods.setAddTime(new Date());
            OrderGoods.setUpdateTime(new Date());
            OrderGoods.setDeleted(false);
            //添加到数据库
            orderGoodsMapper.insertSelective(OrderGoods);

            //创建返回的Vo
            OrderSubmitWxVO orderSubmitWxVO = new OrderSubmitWxVO();
            orderSubmitWxVO.setGrouponLinkId(orderSubmitBO.getGrouponLinkId());
            orderSubmitWxVO.setOrderId(order.getId());


            return orderSubmitWxVO;
        }
        return null;
    }

    /**
     * 订单预支付
     *
     * @param id
     * @param orderId
     * @return  200 支付成功  723支付失败
     */
    @Override
    public int prepay(Integer id, Integer orderId) {
        MarketOrder order = orderMapper.selectByPrimaryKey(orderId);
        //支付时间
        Date payTime = new Date();

            //todo 支付编号
            order.setPayTime(payTime);
            order.setUpdateTime(new Date());
            order.setOrderStatus((short)201);
            //更新订单表的信息
            orderMapper.updateByPrimaryKeySelective(order);
            return 200;
        //支付失败：（todo需要更新订单创建的时间吗）
    }

    @Override
    public OrderListWxVO list(Integer userId, OrderListWxBO orderListWxBO) {

        Integer showType = orderListWxBO.getShowType();
        //根据showType的值查看订单信息
        //0：表示查看全部订单信息，查找deleteId为fasle的订单


            PageHelper.startPage(orderListWxBO.getPage(),orderListWxBO.getLimit());

            MarketOrderExample example = new MarketOrderExample();
            example.setOrderByClause("add_time desc");
            //添加查找条件
            MarketOrderExample.Criteria criteria = example.createCriteria();

            criteria.andDeletedEqualTo(false).andUserIdEqualTo(userId);


         //根据Constant中自定义的方法获取showType对应的订单状态
        // 0：表示查看全部订单信息  非0
        if (showType != 0){
            if (showType != null){
            Short orderStatus = Constant.showType.get(showType);
            criteria.andOrderStatusEqualTo(orderStatus);
            }
        }

        List<MarketOrder> marketOrders = orderMapper.selectByExample(example);

            //获得页码数
            PageInfo<MarketOrder> pageInfo = new PageInfo<>(marketOrders);
            int total = (int) pageInfo.getTotal();
            int pages = pageInfo.getPages();

            //创建返回对象的成员变量的list
            List<OrderListWxVO.ListDTO> list = new ArrayList<>();

            //遍历查找到的订单信息，层层封装
            for (MarketOrder marketOrder : marketOrders) {
                // 获取订单状态(测试是否可行)
                String orderStatus = Constant.orderStatus.get(marketOrder.getOrderStatus());

                //TODO 创建HandleOptionDTO（如何判断 ：取消 支付 删除 评论 确认 退款 重新购买 售后的Boolean值）
                //OrderListWxVO内部类ListDTO的成员变量handleoption
                //OrderListWxVO.ListDTO.HandleOptionDTO handleOptionDTO =
                //        new OrderListWxVO.ListDTO.HandleOptionDTO(false,false,false,
                //                false, false,false,false,false);
                HandleOption handleOptionDTO = OrderHandleOption.handleOption(marketOrder.getOrderStatus());

                //通过OrderId查找Order_goods,获取需要的信息封装进goodsListDTO
                MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
                MarketOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                criteria1.andOrderIdEqualTo(marketOrder.getId());
                List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

                //创建OrderListWxVO内部类ListDTO的成员变量goodsList
                ArrayList<OrderListWxVO.ListDTO.GoodsListDTO> goodsList = new ArrayList<>();

                //遍历marketOrderGoods
                for (MarketOrderGoods OrderGood : marketOrderGoods) {
                    //第一层封装：goodsListDTO
                    OrderListWxVO.ListDTO.GoodsListDTO goodsListDTO = new OrderListWxVO.ListDTO.GoodsListDTO();
                    goodsListDTO.setId(OrderGood.getId());
                    goodsListDTO.setGoodsName(OrderGood.getGoodsName());
                    goodsListDTO.setNumber(OrderGood.getNumber());
                    goodsListDTO.setPicUrl(OrderGood.getPicUrl());
                    goodsListDTO.setSpecifications(OrderGood.getSpecifications());

                    goodsList.add(goodsListDTO);

                }
                //第二层封装：ListDTO  然后放进list中
                OrderListWxVO.ListDTO listDTO = new OrderListWxVO.ListDTO();
                //订单状态
                listDTO.setOrderStatusText(orderStatus);

                listDTO.setAftersaleStatus(marketOrder.getAftersaleStatus());
                //todo 判断是属于团购订单
                listDTO.setGroupin(false);

                listDTO.setOrderSn(marketOrder.getOrderSn());

                listDTO.setId(marketOrder.getId());

                listDTO.setActualPrice(marketOrder.getActualPrice());

                listDTO.setHandleOption(handleOptionDTO);

                listDTO.setGoodsList(goodsList);

                list.add(listDTO);
            }

            //第三层封装，最后返回改对象
            OrderListWxVO orderListWxVO = new OrderListWxVO();
            orderListWxVO.setLimit(orderListWxBO.getLimit());
            orderListWxVO.setPage(orderListWxBO.getPage());
            orderListWxVO.setPages(pages);
            orderListWxVO.setTotal(total);
            orderListWxVO.setList(list);

            return orderListWxVO;

        }

    @Override
    public OrderDetailWxVO detail(Integer orderId) {

        //1.通过orderId查找OrderDetailWxVO成员变量List<MarketOrderGoods> orderGoods
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> OrderGoodsList = orderGoodsMapper.selectByExample(example);

        //2.查找order的信息，用于OrderDetailWxVO成员变量OrderInfoDTO orderInfo(内部类)的封装
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);

        //根据订单状态 ，创建类OrderInfoDTO的成员变量HandleOptionDTO handleOption（内部类）
        Short orderStatus = marketOrder.getOrderStatus();
        HandleOption handleOption = OrderHandleOption.handleOption(orderStatus);

        //3.第一层封装：OrderInfoDTO orderInfo的封装
        OrderDetailWxVO.OrderInfoDTO orderInfoDTO = new OrderDetailWxVO.OrderInfoDTO(
                marketOrder.getConsignee(),marketOrder.getAddress(),
                marketOrder.getAddTime(), marketOrder.getOrderSn(),
                marketOrder.getActualPrice(),marketOrder.getMobile(),
                marketOrder.getMessage(), Constant.orderStatusTxt.get(orderStatus),
                marketOrder.getAftersaleStatus(), marketOrder.getGoodsPrice(),
                marketOrder.getCouponPrice(),marketOrder.getId(),
                marketOrder.getFreightPrice(),handleOption,marketOrder.getShipChannel(),marketOrder.getShipSn());
        //302:用户已收货  、  用户收货时间不为null，设置收获状态为"已收货"，其他情况根据orderstatus判断
        // if (marketOrder.getOrderStatus()== (short)302 && marketOrder.getConfirmTime() != null ){
        //     orderInfoDTO.setOrderStatusText("已收货");
        // }
        //

        //4.第二次封装：OrderDetailWxVO的封装
        OrderDetailWxVO orderDetailWxVO = new OrderDetailWxVO();

        //todo  expressList
        ArrayList<Object> expressList = new ArrayList<>();
        orderDetailWxVO.setExpressInfo(expressList);
        orderDetailWxVO.setOrderGoods(OrderGoodsList);
        orderDetailWxVO.setOrderInfo(orderInfoDTO);

        return orderDetailWxVO;
    }

    /*
     *取消订单
     *
     * @param orderId
     * @return void
     * @author chenxu
     * @since 2022/04/10 13:47
     */
    @Override
    public void cancel(Integer orderId) {
        //取消订单业务实现逻辑：根据orderId，修改订单状态orderstatus
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        //修改订单状态
        marketOrder.setOrderStatus((short)102);
        //修改时间
        marketOrder.setUpdateTime(new Date());

        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }


    @Override
    public void confirm(Integer orderId) {
        //确认收获业务实现逻辑：根据orderId，修改订单状态orderstatus
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        //修改订单状态  302用户收获
        marketOrder.setOrderStatus((short)401);
        //修改时间
        marketOrder.setUpdateTime(new Date());
        //用户确认收货时间
        marketOrder.setConfirmTime(new Date());

        orderMapper.updateByPrimaryKeySelective(marketOrder);

    }


    @Override
    public void delete(Integer orderId) {
        //通过修改订单表中的deleted实现删除业务 true表示删除  false表示存在
        //MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        //marketOrder.setDeleted(true);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        //修改时间
        marketOrder.setUpdateTime(new Date());

        marketOrder.setDeleted(true);

        orderMapper.updateByPrimaryKeySelective(marketOrder);

    }


    @Override
    public MarketOrderGoods getGoods(Integer orderId, Integer goodsId) {
        //根据orderId查找订单表order，获得需要的信息，进行封装和goodsId查找ordergoods
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId).andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(example);

        MarketOrderGoods marketOrderGoods1 = marketOrderGoods.get(0);
        return marketOrderGoods1;
    }

    @Transactional
    @Override
    public void comment(OrderCommentBO orderComment) {
        //评价业务逻辑：获取订单评价信息，添加到数据库，并修改order表和ordergoods表的评价信息状态
        // 根据OrderGoogsId获取orderId
        MarketOrderGoods OrderGoods = orderGoodsMapper.selectByPrimaryKey(orderComment.getOrderGoodsId());
        boolean hasPicture = orderComment.isHasPicture();
        //order
        MarketOrder order = orderMapper.selectByPrimaryKey(OrderGoods.getOrderId());

        //进行封装，然后添加到数据库对应的表中
        MarketComment marketComment = new MarketComment(null,0,(byte)0, orderComment.getContent(),
            null,order.getUserId(),hasPicture,orderComment.getPicUrls(),orderComment.getStar(),
             new Date(),new Date(),false);
        commentMapper.insertSelective(marketComment);

        //修改ordergoods中字段comment，设置为comment表中的id
        OrderGoods.setComment(marketComment.getId());
        OrderGoods.setUpdateTime(new Date());
        orderGoodsMapper.updateByPrimaryKey(OrderGoods);

        //修改order中的comment相关信息  待评价订单商品数量-1
        if (order.getComments() != null){
        Short comments = (short)(order.getComments() - 1);
        order.setComments(comments);
        }
        order.setUpdateTime(new Date());
        //修改订单状态；评价说明订单完成设置为501
        order.setOrderStatus((short)501);
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public void refund(Integer userId, Integer orderId) {
        //已支付待发货的订单：申请退款   退款+退优惠券
        MarketOrder order = orderMapper.selectByPrimaryKey(orderId);

        //退款金额为订单商品费用+运费
        order.setRefundAmount(order.getGoodsPrice().add(order.getFreightPrice()));

        //设置订单状态码为 202：申请退款
        order.setOrderStatus((short)202);

        order.setAftersaleStatus((short) 1);

        // 售后编号;先获取当前时间的年月日，在随机生成一个6位数，进行拼接
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMdd");
        String format = dateFormat.format(date);

        //7.随机生成一个六位数
        Random random = new Random();
        String result="";
        int length = 6;
        for (int i=0;i<length;i++) {
            result+=random.nextInt(10);
        }
        //获得订单编号：拼接时间和随机生成的六位数
        String aftersn = format + result;

        //status :1 表示用户已经申请
        MarketAftersale marketAftersale = new MarketAftersale();
        marketAftersale.setOrderId(orderId);
        marketAftersale.setStatus((short)1);
        marketAftersale.setAddTime(new Date());
        marketAftersale.setAmount(order.getGoodsPrice());
        marketAftersale.setDeleted(false);
        marketAftersale.setAftersaleSn(aftersn);
        marketAftersale.setType((short)0);
        marketAftersale.setUserId(userId);

        aftersaleMapper.insertSelective(marketAftersale);

        //修改订单状态的售后状态aftersale为1:表示用户已经申请售后

        orderMapper.updateByPrimaryKeySelective(order);

    }


}
